package org.jeecg.tender.taskJob.bdebid;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.util.HttpClientUtil;
import org.jeecg.common.util.JacksonUtil;
import org.jeecg.tender.config.WebDriverConfig;
import org.jeecg.tender.information.entity.TenderInformation;
import org.jeecg.tender.information.service.ITenderInformationService;
import org.jeecg.tender.keyword.service.ITenderSecurityKeywordManagementService;
import org.jeecg.tender.project.dto.req.SendProjectNoticeReqDto;
import org.jeecg.tender.project.service.ITenderProjectNoticeService;
import org.jeecg.tender.taskJob.bdebid.support.BdebidResp;
import org.jeecg.tender.taskJob.bdebid.support.BdebidRespInfo;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class BdebidTaskJob implements Job {

    @Resource
    private ITenderInformationService tenderInformationService;
    @Resource
    private ITenderSecurityKeywordManagementService tenderSecurityKeywordManagementService;
    @Autowired
    private WebDriverConfig webDriverConfig;
    @Resource
    private ITenderProjectNoticeService tenderProjectNoticeService;

    /**
     * <a href="https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json">google浏览器驱动下载地址</a>
     **/
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        WebDriver driver = null;
        List<SendProjectNoticeReqDto> noticeInfoList = new ArrayList<>();
        try {
            driver = webDriverConfig.driver();
            Map<Long, String> lableMap = tenderSecurityKeywordManagementService.getCacheSecurityKeywordManagement();

            List<BdebidRespInfo> list = null;
            int current = 0;
            do {
                String url = "https://www.bdebid.com/EpointWebBuilder5_1/rest/commonSearch/getInfoList";
                Map<String, Object> params = new HashMap<>(4);
                params.put("categorynum", "003001");
                params.put("title", "");
                // 每次抽最近一周的记录
                params.put("datetime", "近一周");
                params.put("codearea", "");
                params.put("hangye", "");
                params.put("pageIndex", current);
                params.put("pageSize", 17);

                Map<String, Object> paramJson = new HashMap<>();
                paramJson.put("params", JacksonUtil.toJsonString(params));
                TypeReference<BdebidResp<BdebidRespInfo>> type = new TypeReference<BdebidResp<BdebidRespInfo>>(){};
                BdebidResp<BdebidRespInfo> resp = HttpClientUtil.postFormData(url, paramJson, type);
                if (resp.getStatus() == 1) {
                    list = resp.getInfodata();
                    for (BdebidRespInfo req : list) {
                        // 检查时间范围
                        long count = tenderInformationService.lambdaQuery().eq(TenderInformation::getTenderTitle, req.getTitle()).count();
                        if (count > 0) {
                            log.info("{}已经抓取", req.getTitle());
                            continue;
                        }
                        List<Long> lableList = lableMap.entrySet().stream()
                                .filter(entry -> req.getTitle().contains(entry.getValue())).map(Map.Entry::getKey)
                                .collect(Collectors.toList());
                        if (ObjectUtils.isEmpty(lableList)) {
                            log.debug("{}没有安全标签", req.getTitle());
                            continue;
                        }

                        String detailUrl = String.format("https://www.bdebid.com%s", req.getInfourl());
                        driver.get(detailUrl);
                        driver.navigate().refresh();
                        try {
                            // 等待页面加载完成
                            WebElement element = new WebDriverWait(driver, Duration.ofSeconds(20))
                                    .until(ExpectedConditions.presenceOfElementLocated(By.cssSelector(".ewb-list-main")));
                            // 获取招标文书
                            String  executor = (String) ((JavascriptExecutor) driver).executeScript("return arguments[0].outerHTML;", element);
                            tenderInformationService.saveBdebid("比德电子采购平台", executor, "html", lableList, req, noticeInfoList,detailUrl);
                        } catch (Exception e) {
                            log.warn("抓取{}明细失败; 错误原因", req.getTitle(), e);
                        }
                    }
                }
                current++;
            } while (ObjectUtils.isNotEmpty(list));



        } finally {
            // 发送通知
            tenderProjectNoticeService.sendTenderProjectNotice(noticeInfoList);
            // 需要正确关闭edge; 否则会导致电脑开启进程过多而卡死
            if (driver != null) {
                driver.quit();
            }
            HttpClientUtil.close();
            log.info("比德采购平台爬取任务结束");
        }
    }
}
